package com.tiger.common;


import com.tiger.utils.Md5;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;

@Service
public class UploadService {
    @Value("${Upload.dist}")
    private String dist;


    public void del(String fileName) {
        File file = new File(String.valueOf(Paths.get(dist, fileName)));
        file.delete();
    }

    public String put(MultipartFile file, String flag) {

        LocalDate today = LocalDate.now();
        // 获取当前年份
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();


        String monthStr = String.valueOf(month);
        String dayStr = String.valueOf(day);
        if(month < 10) {
            monthStr = "0" + monthStr;
        }
        if(day < 10) {
            dayStr = "0" + dayStr;
        }

        //2024/03/10
        String subDir = String.valueOf(Paths.get(String.valueOf(year), monthStr, dayStr));


        File dir = new File(String.valueOf(Paths.get(dist, subDir)));
        dir.mkdirs();


        Instant now = Instant.now();
        long time = now.getEpochSecond();

        String originalFilename = file.getOriginalFilename();

        String fileName = String.valueOf(Paths.get(subDir, Md5.generate(time + "&" + originalFilename + "&" + flag) + "." + getFileExtension(originalFilename)));

        System.out.println(String.valueOf(Paths.get(dist, fileName)));

        File filePath = new File(String.valueOf(Paths.get(dist, fileName)));


        try {
            file.transferTo(filePath);
            System.out.println("文件上传成功！");
        } catch (IOException e) {
            System.out.println("文件上传失败，请重试！");
        }

        return fileName;
    }

    private static String getFileExtension(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1);
        }
        return "";
    }
}
